package com.ideafactory.client.ybservice.ybviewpager;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gprinter.command.EscCommand;
import com.gprinter.command.GpUtils;
import com.ideafactory.client.afinal.NetConstants;
import com.ideafactory.client.beans.OrderBaseInfoBean;
import com.ideafactory.client.beans.OrderGoodsBean;
import com.ideafactory.client.print.icod.IcodPrinterManager;
import com.ideafactory.client.utils.FileConstants;
import com.ideafactory.client.utils.JsonForBean;
import com.ideafactory.client.utils.SpUtils;
import com.ideafactory.client.utils.netutils.MyCallBack;
import com.ideafactory.client.utils.netutils.NetUtils;
import com.ideafactory.client.ybselfservice.R;
import com.ideafactory.client.ybservice.YbSelfService;
import com.lidroid.xutils.util.LogUtils;

import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;


/**
 * Created by LiuShao on 2016/5/24.
 */
public class GoodsPayPager extends GoodsBasePager{

    private static final String TAG = "GoodsPayPager";

    @ViewInject(R.id.iv_cancel)
    private ImageView iv_cancel;

    @ViewInject(R.id.tv_minsecond)
    private TextView tv_minsecond;

    @ViewInject(R.id.tv_totalMoney)
    private TextView tv_totalMoney;

    @ViewInject(R.id.tv_allmoney_wechat)
    private TextView tv_allmoney_wechat;

    @ViewInject(R.id.tv_allmoney_alipay)
    private TextView tv_allmoney_alipay;


    @ViewInject(R.id.iv_alipay)
    private ImageView iv_alipay;

    @ViewInject(R.id.iv_wechat)
    private ImageView iv_wechat;


    @ViewInject(R.id.iv_scanleGun)
    private ImageView iv_scanleGun;

    private Timer timer;
    private int conunt = 90;//倒计时90s

    public static Handler mPayingHandler;

    private ImageOptions options;
    private static StringBuffer sb = null;//扫描机扫描

    private Handler handler;

    public GoodsPayPager(Context context) {
        super(context);
    }
    @Override
    public View initView() {
        View view = View.inflate(context, R.layout.fragment_payment,null);
        x.view().inject(this, view);
        return view;
    }
    @Override
    public void initViewBuind() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        try {
                            String info = context.getResources().getString(R.string.lzfwchs)+" <font color='#079c62'>" + msg.arg1+ "</font> "+context.getResources().getString(R.string.miao);
                            if (tv_minsecond != null) {
                                tv_minsecond.setText(Html.fromHtml(info));
                            }
                            if (msg.arg1 == 0) {
                                changePosition(-1);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case 2:
                        String payinfo = (String) msg.obj;
                        Log.e(TAG, "payinfo-----------> "+payinfo );
                        JSONObject jobject = JSON.parseObject(payinfo);
                        if (jobject.getString("status").equals("1")) {
                            if (baseInfoBean != null) {
                                if (baseInfoBean.getOrderSernum().equals(jobject.getString("orderSernum"))) {
                                    Map map=new HashMap();
                                    map.put("orderSernum",jobject.getString("orderSernum"));
                                    NetUtils.Post(NetConstants.GETORDERINFO, map, new MyCallBack<String>() {
                                        @Override
                                        public void onSuccess(String result) {
                                            JSONObject jsonObject = JSON.parseObject(result);
                                            Log.e(TAG, "result---------->"+result );
                                            JSONObject   json = jsonObject.getJSONObject("orderBaseInfo");

                                            String shopName = SpUtils.getString(context, SpUtils.SHOP_NAME, "");
                                            String shopAddress = SpUtils.getString(context, SpUtils.SHOP_ADDRESS, "");
                                            try {
                                                File file = new File(FileConstants.SHOPIMG_CACHE_PATH + "shopimg.jpg");
                                                Log.e(TAG, "jsonArray-->"+jsonArray.toString() );

                                                double allMoney=baseInfoBean.getAllMoney()+baseInfoBean.getPreMoney();
                                                double realMoney = 0d;

                                                for (int i = 0; i < mList.size(); i++) {
                                                    realMoney = realMoney + mList.get(i).getPrice() * mList.get(i).getCount();
                                                }

                                                realMoney = realMoney + baseInfoBean.getPackMoney();

                                                Log.e(TAG, "realMoney------------->" + realMoney);

                                                int isPrint = SpUtils.getInt(context, SpUtils.ISPRINT, 1);
                                                Log.e(TAG, "isPrint-------------->" + isPrint);
                                                if (isPrint == 1) {
                                                    YbSelfService.printSeatTest(mList, YbSelfService.mUsbDev1, shopName, shopAddress, baseInfoBean.getAllMoney() + "", json.getString("orderCallNum"), baseInfoBean.getPackMoney() + "", baseInfoBean.getIsPack(), baseInfoBean.getPreMoney() + "", realMoney + "");
                                                    IcodPrinterManager.getIns().printText(mList, YbSelfService.mUsbDev1, shopName, shopAddress, baseInfoBean.getAllMoney() + "", baseInfoBean.getOrderSernum().replaceAll("busself", ""), baseInfoBean.getPackMoney() + "", baseInfoBean.getIsPack(), baseInfoBean.getPreMoney() + "", realMoney + "");
                                                }


                                                for (int i = 0; i <mList.size() ; i++) {
                                                    printWifiInfo(mList.get(i).getName(),mList.get(i).getCount(),baseInfoBean.getIsPack(), json.getString("orderCallNum"));
                                                }


                                                HashMap map2 = new HashMap();
                                                String sb = SpUtils.getString(context, SpUtils.DEVICENO, "");
                                                map2.put("deviceId", sb);
                                                map2.put("orderId", orderId + "");

                                                NetUtils.Post(NetConstants.PostTicketInfo, map2, new MyCallBack<String>() {
                                                    @Override
                                                    public void onSuccess(String result) {
                                                        System.out.println("小票成功!");
                                                    }
                                                    @Override
                                                    public void onError(Throwable ex, boolean isOnCallback) {
                                                        System.out.println("小票失败！");
                                                    }

                                                });

                                                YbSelfService.speak(context.getResources().getString(R.string.paySuccess));
                                                if (mCurrentPosition==GOODS_PAY_INT){
                                                    changePosition(GOODS_PAY_SCUESS_INT);
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }

                                    });

                                }
                            }
                        } else {
                        }
                        break;
                }
            }
        };

        mPayingHandler = handler;
        YbSelfService.setOnReceicedKeyDown(new YbSelfService.OnReceicedKeyDown() {
            @Override
            public void OnKeyDown(int keyCode, KeyEvent event) {
                onKeyDown(keyCode,event);
            }
        });

        options = new ImageOptions.Builder()
                //设置加载失败后的图片
                .setUseMemCache(false)
                .setIgnoreGif(false)
                .build();
    }

   public static  int isScanle;
    @Override
    public void initData(int originPosition) {
        x.image().bind(iv_wechat, "assets://loading_qr.gif", options);
        x.image().bind(iv_alipay, "assets://loading_qr.gif", options);
        sb = new StringBuffer();
        conunt = 90;
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    conunt--;
                    Message msg = new Message();
                    msg.what = 1;
                    msg.arg1 = conunt;
                    handler.sendMessage(msg);

                }
            }, 1000, 1000);

        }
        isScanle = SpUtils.getInt(context, SpUtils.ISONLINEPAY, 0);
        if (isScanle == 2) {
            iv_scanleGun.setVisibility(View.GONE);
        }
        goodsInfo = (String)getObj(GOODS_ENSURE_INT);
        if (goodsInfo != null) {
            try {
                JSONObject jsonObject = JSON.parseObject(goodsInfo);
                Log.e(TAG, "goodsInfo------>"+goodsInfo );
                baseInfoBean = JsonForBean.getPerson(jsonObject.getString("orderBaseInfo"), OrderBaseInfoBean.class);

                if (baseInfoBean.getAllMoney() <= 0d) {

                    Log.e(TAG, "baseInfoBean.getAllMoney()==0d------------------ ");
                    HashMap map = new HashMap();
                    map.put("orderId", baseInfoBean.getId() + "");
                    NetUtils.Post(NetConstants.SUBMIT_0_ORFER, map, new MyCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            JSONObject jobject = JSONObject.parseObject(result);
                            Log.e(TAG, "SUBMIT_0_ORFER-------->" + result);

                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            Log.e(TAG, "SUBMIT_0_ORFER------------onError--->" + ex.getMessage());

                        }
                    });
                    tv_allmoney_alipay.setText(context.getResources().getString(R.string.xf) + baseInfoBean.getAllMoney() + " " + context.getResources().getString(R.string.yuan));
                    tv_allmoney_wechat.setText(context.getResources().getString(R.string.xf) + baseInfoBean.getAllMoney() + " " + context.getResources().getString(R.string.yuan));
                    jsonArray = jsonObject.getJSONArray("orderGoodsList");
                    mList = JsonForBean.getPersonList(jsonArray.toString(), OrderGoodsBean.class);
                    mHashmap = (HashMap<String, List<OrderGoodsBean>>) getListByKey(mList);

                    for (String key : mHashmap.keySet()) {
                        Log.e(TAG, "key---------->" + key);
                        List<OrderGoodsBean> list = mHashmap.get(key);
                        for (OrderGoodsBean bean : list) {
                            Log.e(TAG, "bean-----------> " + bean.getName());
                        }
                    }


                    String path = FileConstants.CAllNumQR_CACHE_PATH;
                    File file = new File(path);
                    if (file.exists() == false) {
                        file.mkdirs();
                    }
                    String filepath = path + "cash.jpg";
                    File fileNew = new File(filepath);
                    if (fileNew.exists()) {
                        file.delete();
                    }
                    NetUtils.DownLoadFile(baseInfoBean.getOrderCodeUrl(), filepath, new MyCallBack<File>() {
                        @Override
                        public void onSuccess(File result) {
                            super.onSuccess(result);
                            Log.e("下载成功", "");
                        }
                    });
                    orderId = baseInfoBean.getId();


                } else {


                tv_allmoney_alipay.setText( context.getResources().getString(R.string.xf)+baseInfoBean.getAllMoney()+" "+context.getResources().getString(R.string.yuan));
                tv_allmoney_wechat.setText(context.getResources().getString(R.string.xf)+baseInfoBean.getAllMoney()+" "+context.getResources().getString(R.string.yuan));
                jsonArray = jsonObject.getJSONArray("orderGoodsList");
                mList = JsonForBean.getPersonList(jsonArray.toString(), OrderGoodsBean.class);
                mHashmap= (HashMap<String, List<OrderGoodsBean>>) getListByKey(mList);

                for (String key: mHashmap.keySet()) {
                    Log.e(TAG, "key---------->"+key );
                    List<OrderGoodsBean> list=mHashmap.get(key);
                    for (OrderGoodsBean bean:list) {
                        Log.e(TAG, "bean-----------> "+bean.getName() );
                    }
                }


                String path = FileConstants.CAllNumQR_CACHE_PATH;
                File file = new File(path);
                if (file.exists() == false) {
                    file.mkdirs();
                }
                String filepath = path + "cash.jpg";
                File fileNew = new File(filepath);
                if (fileNew.exists()) {
                    file.delete();
                }
                NetUtils.DownLoadFile(baseInfoBean.getOrderCodeUrl(), filepath, new MyCallBack<File>() {
                    @Override
                    public void onSuccess(File result) {
                        super.onSuccess(result);
                        Log.e("下载成功","");
                    }
                });

                    HashMap map2 = new HashMap();

                    map2.put("orderId", baseInfoBean.getId() + "");
                orderId = baseInfoBean.getId();

                int isAlipay=  SpUtils.getInt(context, SpUtils.ISALIPAY,0);
                if (isAlipay==1){
                    NetUtils.Post(NetConstants.getAlipayQRcode, map2, new MyCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            JSONObject jobject = JSONObject.parseObject(result);
                            Log.e(TAG, "支付宝-------->"+result );
                            if (jobject.getString("status").equals("1")) {

                                x.image().bind(iv_alipay, jobject.getString("codeUrl"), options);
                            }
                        }
                    });
                }else {
                    iv_alipay.setImageResource(R.mipmap.ticket_notallow);
                }

                int isWxPay=  SpUtils.getInt(context, SpUtils.ISWXPAY,0);
                if (isWxPay==1){
                    NetUtils.Post(NetConstants.getWeiChatQRcode, map2, new MyCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            JSONObject jobject = JSONObject.parseObject(result);
                            Log.e(TAG, "微信-------->"+result );
                            if (jobject.getString("status").equals("1")) {
                                x.image().bind(iv_wechat, jobject.getString("codeUrl"), options);
                            }
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            System.out.println("result2222222--->" + "失败！");
                            Log.e(TAG, "result2222222--------------->" + ex.getMessage());

                        }
                    });
                }else {
                    iv_wechat.setImageResource(R.mipmap.ticket_notallow);
                }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        clearObj();
    }
    public  Map getListByKey(List list) {
        Map map = new HashMap();
        for (int i = 0; list != null && i < list.size(); i++) {
            OrderGoodsBean obj = (OrderGoodsBean) list.get(i);
            String key = obj.getWindowName();
            if (map.containsKey(key)) {
                List lists = (List) map.get(key);
                lists.add(obj);
            } else {
                List lists = new ArrayList();
                lists.add(obj);
                map.put(key, lists);
            }
        }
        return map;
    }

    private String goodsInfo = null;

    private OrderBaseInfoBean baseInfoBean = null;
    private List<OrderGoodsBean> mList = null;
    private HashMap<String,List<OrderGoodsBean>> mHashmap = null;
    private List<List<OrderGoodsBean>> mAllList = null;
    private JSONArray jsonArray;
    public static int orderId;
    private static  long startTime=0l;
    public static boolean onKeyDown(int keyCode, KeyEvent event) {

        System.out.println("keyCode:" + (keyCode - 7) + " ");

        if (keyCode != 82 && keyCode != 4) {
            Log.e(TAG, "时间开始------> "+System.currentTimeMillis() );
            if (sb != null) {
                sb.append((keyCode - 7) + "");
                if (sb.length()==1){
                    startTime=System.currentTimeMillis();
                    Log.e(TAG, "startTime------>"+startTime);
                }
                if (sb.length() == 18) {
                    long  endTime=System.currentTimeMillis();
                    if (endTime-startTime>500){
                        Log.e(TAG, "endTime------>"+endTime+ "      ,   startTime------>"+startTime);
                        sb.delete(sb.toString().length()-1,sb.toString().length());
                    }
                    Log.e(TAG, "sb------------->" + sb);
                    HashMap map = new HashMap();
                    map.put("auth_code", sb.toString());
                    map.put("orderId", orderId + "");
                    System.out.println("orderId---->" + orderId);
                    System.out.println("sb------------->" + sb);
                    if (sb.toString().startsWith("28")) {
                        NetUtils.Post(NetConstants.AlipayScancode, map,new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                System.out.println("支付宝扫码成功");
                            }
                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                System.out.println("支付宝扫码失败");
                                System.out.println("ex---->" + ex.getMessage().toString());
                            }
                        });
                    } else if (sb.toString().startsWith("13")) {
                        NetUtils.Post(NetConstants.WechatScancode, map, new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                System.out.println("微信扫码成功");
                            }
                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                System.out.println("微信扫码失败");
                                System.out.println("ex---->" + ex.getMessage().toString());
                            }
                        });
                    }

                    sb.delete(0, sb.toString().length());
                }
                return true;
            }


        }
        return false;
    }



    @Event(R.id.iv_cancel)
    private void onClick(View view) {
        changePosition(-1);
    }
    void changePosition(int position){
        if (timer!=null){
            timer.cancel();
            timer = null;
        }

        if (sb!=null){
            sb=null;
        }
        onPagerChange.changePositon(GoodsBasePager.GOODS_PAY_INT,position);
    }


    private void printWifiInfo(String name,int count,int ispack,String num){
        EscCommand esc = new EscCommand();
        esc.addInitializePrinter();
        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);// 设置打印居中
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);// 设置为倍高倍宽
        esc.addText("点菜单\n"); // 打印文字
        esc.addText("----------------\n"); // 打印文字
        esc.addText("牌号:"+num+"\n"); // 打印文字
        esc.addText("桌台:自助机\n"); // 打印文字
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");// 设置日期格式
        esc.addText("时间:"+df.format(new Date())+"\n"); // 打印文字
        esc.addText("----------------\n"); // 打印文字
        esc.addText("1:"+name+ "*"+count+"\n"); // 打印文字
        esc.addText("----------------\n"); // 打印文字
        if (ispack==1){
            esc.addText("#打包\n"); // 打印文字

        }else{
            esc.addText("#堂食\n"); // 打印文字
        }
        esc.addPrintAndFeedLines((byte)3);
        esc.addCutAndFeedPaper((byte) 1);//设置切纸后走纸
        Vector<Byte> datas = esc.getCommand(); // 发送数据
        byte[] bytes = GpUtils.ByteTo_byte(datas);
        String sss = Base64.encodeToString(bytes, Base64.DEFAULT);
        int rs;
        try {
//            rs = YbSelfService.mGpService.sendEscCommand(0, sss);
//            GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rs];
//            if (r != GpCom.ERROR_CODE.SUCCESS) {
////                Toast.makeText(context, GpCom.getErrorText(r), Toast.LENGTH_SHORT).show();
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
